package com.zzl.springboot.utils;

import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

//SSM环境使用的上传和下载
public class UpDownUtil {
    //springboot通过虚拟地址 获取真实路径
    public static String getPath(){
        String rootPath=null;
        try {
            //springboot由于是内置tomcat 地址是虚拟的
            rootPath= ResourceUtils.getURL("classpath:")
                    .getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


        File rootFile=new File(rootPath);
        String path=rootFile.getAbsolutePath()+"/static/upload";
        return path;
    }

    public static String upload(HttpServletRequest req, MultipartFile myFile){
        //SSM环境 使用这种方式的地址 因为tomcat自己搭建的
        //String path=req.getServletContext().getRealPath("/upload");
        File f=new File(getPath());
        if(!f.exists()) f.mkdirs();
        //获取上传文件名 等价于servlet中哪个方法
        String oldName=myFile.getOriginalFilename();
        if(oldName.isEmpty()) return null;
        String suffix=oldName.substring(oldName.lastIndexOf("."));
        String newName= UUID.randomUUID().toString() +suffix;
        try {
            myFile.transferTo(new File(getPath()+File.separator+newName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newName;
    }
    public static void download(HttpServletRequest req
            , HttpServletResponse resp
            , String fileName){
        try {
            //2.获取文件真实路径
            String filePath=getPath()+File.separator+fileName;
            //2.1  设置响应格式(                      设置附件下载，指定下载后的文件名)
            //text/html;charset=utf-8
            resp.setHeader("content-disposition","attachment;filename="+fileName);
            //3.通过IO字节流做文件传输
            ServletOutputStream sos=resp.getOutputStream();
            FileInputStream fis=new FileInputStream(filePath);
            byte[] b=new byte[1024];
            int len=0;
            while((len=fis.read(b))!=-1){
                sos.write(b,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
